package com.party.admin.task;

import com.party.common.utils.BigDecimalUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.PackageCount;
import com.party.core.model.system.TargetType;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IPackageCountService;
import com.party.notify.notifyPush.officialPartner.IOfficialPartnerNotifySendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author： yifeng
 * @description： 机构短信预警
 * @date：Created in  2017/12/13 下午 16:44
 **/
@Service(value = "qartzOrgSmsWarn")
public class QuartzOrgSmsWarn {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IPackageCountService packageCountService;
    @Autowired
    private IOfficialPartnerNotifySendService officialPartnerNotifySendService;

    public void run() {
        logger.info("预警定时任务启动");
        try {
            List<MemberGroup> members = memberGroupService.getAllPartnerNoOpenStatus();
            for (MemberGroup member : members) {
                PackageCount packageCount = packageCountService.getUnique(new PackageCount(member.getId(), TargetType.PUSH_SMS.getCode()));
                if (packageCount != null && YesNoStatus.YES.getCode().equals(packageCount.getIsOpen())) {
                    if (null != packageCount.getWarnNum()) {
                        double percent = BigDecimalUtils.div(packageCount.getWarnNum(), 100);
                        double percentResult = BigDecimalUtils.mul(packageCount.getTempTotalNum(), percent);
                        int warnNum = (int) Math.round(percentResult);

                        int spareNum = packageCount.getTotalNum() - packageCount.getUseNum();
                        if (spareNum <= warnNum) {
                            officialPartnerNotifySendService.sendSmsWarn(member.getRealname(), member.getMobile(), member.getId(), spareNum);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("预警定时任务异常", e);
        }
    }
}
